package com.situ.wms.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.wms.impl.ManagerServiceImpl;
import com.situ.wms.service.ManagerService;
import com.situ.wms.util.DBUtil;

@WebServlet("/login")
public class LoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	//get的方式表示需要返回登录界面，post方式表示需要验证用户名密码
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("WEB-INF/login.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String captcha = request.getParameter("captcha");
		System.out.println(captcha);
		System.out.println(request.getSession().getAttribute("captchaSession"));
		if (!((String)(request.getSession().getAttribute("captchaSession"))).equals(captcha)) {
			request.setAttribute("msg", "验证码错误，请重新输入！");
			request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
		} else {

			ManagerService service = new ManagerServiceImpl();
			password = DBUtil.md5(password);
			Boolean right = service.check(username, password);
			//派service校验是否正确
			if (right) {
				//保存一下这个用户登录成功了
				request.getSession().setAttribute("currentManager", username);
				response.sendRedirect("/index");
			} else {
				request.setAttribute("msg", "用户名或密码错误！");
				request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);

			}
		}
	}
}
